import { useState, useEffect } from 'react'

interface FloatingAIConfig {
  isEnabled: boolean
  position: { x: number; y: number }
  autoHide: boolean
  showQuickActions: boolean
}

const defaultConfig: FloatingAIConfig = {
  isEnabled: true,
  position: { x: 20, y: 20 },
  autoHide: false,
  showQuickActions: true
}

const STORAGE_KEY = 'floating-ai-config'

export function useFloatingAIConfig() {
  const [config, setConfig] = useState<FloatingAIConfig>(defaultConfig)
  const [isLoaded, setIsLoaded] = useState(false)

  // 从localStorage加载配置
  useEffect(() => {
    try {
      const savedConfig = localStorage.getItem(STORAGE_KEY)
      if (savedConfig) {
        const parsedConfig = JSON.parse(savedConfig)
        setConfig({ ...defaultConfig, ...parsedConfig })
      }
    } catch (error) {
      console.error('Failed to load floating AI config:', error)
    } finally {
      setIsLoaded(true)
    }
  }, [])

  // 保存配置到localStorage
  const updateConfig = (newConfig: Partial<FloatingAIConfig>) => {
    const updatedConfig = { ...config, ...newConfig }
    setConfig(updatedConfig)
    
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(updatedConfig))
    } catch (error) {
      console.error('Failed to save floating AI config:', error)
    }
  }

  // 重置配置
  const resetConfig = () => {
    setConfig(defaultConfig)
    try {
      localStorage.removeItem(STORAGE_KEY)
    } catch (error) {
      console.error('Failed to reset floating AI config:', error)
    }
  }

  // 切换启用状态
  const toggleEnabled = () => {
    updateConfig({ isEnabled: !config.isEnabled })
  }

  // 更新位置
  const updatePosition = (position: { x: number; y: number }) => {
    updateConfig({ position })
  }

  // 切换自动隐藏
  const toggleAutoHide = () => {
    updateConfig({ autoHide: !config.autoHide })
  }

  // 切换快速操作显示
  const toggleQuickActions = () => {
    updateConfig({ showQuickActions: !config.showQuickActions })
  }

  return {
    config,
    isLoaded,
    updateConfig,
    resetConfig,
    toggleEnabled,
    updatePosition,
    toggleAutoHide,
    toggleQuickActions
  }
}
